const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;

class Countdown {
    private endTime: number;
    private timer!: number;
    public constructor(endDate: number | string | Date) {
        if (typeof endDate === 'number' && endDate && endDate.toString().length < 13) {
            endDate = Number(endDate.toString().concat('000'));
        }
        if (typeof endDate === 'string') {
            endDate = endDate.replace(/-/g, '/');
        }
        const date = new Date(endDate);
        this.endTime = date.getTime();
    }

    /**
     * 开始倒计时
     */
    public start(callback: (data: Data) => void) {
        const run = () => {
            const dur = Math.round((this.endTime - Date.now()));
            if (dur > 0) {
                const d = Math.floor(dur / DAY);
                const h = Math.floor((dur % DAY) / HOUR);
                const i = Math.floor((dur % HOUR) / MINUTE);
                const s = Math.floor((dur % MINUTE) / SECOND);
                callback({
                    d,
                    h,
                    i,
                    s,
                });
            } else {
                clearInterval(this.timer);
            }

        }
        run();
        this.timer = window.setInterval(() => run(), 1000);
    }
    /**
     * 清除倒计时
     */
    public clear() {
        if (this.timer) {
            clearInterval(this.timer);
        }
    }
}



export default class CountdownUtils {
    private static instance: CountdownUtils;
    public static getInstance() {
        if (!this.instance) {
            this.instance = new CountdownUtils();
        }
        return this.instance;
    }

    private constructor() {

    }
    /**
     * 创建倒计时
     * @param endDate 
     */
    public create(endDate: number | string | Date) {
        return new Countdown(endDate);
    }

}

interface Data {
    d: number,
    h: number,
    i: number,
    s: number,
}
